// adapter/rest/BorrowRecordController.java
package com.library.bookservice.adapter.rest;

import com.library.bookservice.application.service.BorrowService;
import com.library.bookservice.domain.model.BorrowRecord;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 借阅记录REST控制器
 * 处理借阅相关的HTTP请求
 */
@RestController
@RequestMapping("/api/v1/borrow-records")
public class BorrowRecordController {

    private final BorrowService borrowService;

    public BorrowRecordController(BorrowService borrowService) {
        this.borrowService = borrowService;
    }

    @PostMapping("/borrow")
    public ResponseEntity<BorrowRecordResponse> borrowBook(@Valid @RequestBody BorrowBookRequest request) {
        BorrowRecord record = borrowService.borrowBook(
                request.bookId(),
                request.borrowerName(),
                request.borrowerPhone()
        );
        BorrowRecordResponse response = BorrowRecordResponse.from(record);
        return ResponseEntity.status(HttpStatus.CREATED).body(response);
    }

    @PostMapping("/{id}/return")
    public ResponseEntity<BorrowRecordResponse> returnBook(@PathVariable Long id) {
        BorrowRecord record = borrowService.returnBook(id);
        BorrowRecordResponse response = BorrowRecordResponse.from(record);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/book/{bookId}")
    public ResponseEntity<List<BorrowRecordResponse>> getRecordsByBookId(@PathVariable Long bookId) {
        List<BorrowRecord> records = borrowService.getBorrowRecordsByBookId(bookId);
        List<BorrowRecordResponse> responses = records.stream()
                .map(BorrowRecordResponse::from)
                .toList();
        return ResponseEntity.ok(responses);
    }

    @GetMapping("/borrower/{borrowerName}")
    public ResponseEntity<List<BorrowRecordResponse>> getRecordsByBorrower(@PathVariable String borrowerName) {
        List<BorrowRecord> records = borrowService.getBorrowRecordsByBorrower(borrowerName);
        List<BorrowRecordResponse> responses = records.stream()
                .map(BorrowRecordResponse::from)
                .toList();
        return ResponseEntity.ok(responses);
    }

    @GetMapping("/active")
    public ResponseEntity<List<BorrowRecordResponse>> getActiveRecords() {
        List<BorrowRecord> records = borrowService.getActiveBorrowRecords();
        List<BorrowRecordResponse> responses = records.stream()
                .map(BorrowRecordResponse::from)
                .toList();
        return ResponseEntity.ok(responses);
    }
}